package com.hoyue.servlet;

import com.hoyue.bean.User;
import com.hoyue.service.UserService;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@WebServlet("/UserServlet")
public class UserServlet extends HttpServlet {

	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String name = request.getParameter("method");//获取方法名
		if (name == null || name.isEmpty()) {
			throw new RuntimeException("没有传递method参数,请给出你想调用的方法");
		}
		Class c = this.getClass();//获得当前类的Class对象
		Method method = null;
		try {
			//获得Method对象
			method = getClass().getDeclaredMethod(name, HttpServletRequest.class, HttpServletResponse.class);
		} catch (Exception e) {
			throw new RuntimeException("没有找到" + name + "方法，请检查该方法是否存在");
		}

		try {
			method.invoke(this, request, response);//反射调用方法
		} catch (Exception e) {
			System.out.println("你调用的方法" + name + ",内部发生了异常");
			throw new RuntimeException(e);
		}
	}

	UserService userService = new UserService();

	protected void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");

		String userName = request.getParameter("username");
		String password = request.getParameter("password");

		User user = userService.loginUser(userName, password);

		if (user != null) {
			//登录成功
			request.getSession().setAttribute("user", user);
			request.setAttribute("userId",user.getId());
			request.getRequestDispatcher(request.getContextPath() + "/WEB-INF/admin/index.jsp").forward(request, response);
			System.out.println("successfully");
		} else { //帐号或者密码错误
			String str = "账号密码错误";
			request.setAttribute("message", str);
			request.getRequestDispatcher("/login.jsp").forward(request, response);
		}
	}

	protected void changeSelf(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		double randomNum = Math.random();
		request.setAttribute("randomNum", randomNum);
		request.getRequestDispatcher("/WEB-INF/admin/yourself.jsp").forward(request, response);
	}

	protected void updateUser(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		User olduser = (User) request.getSession().getAttribute("user");
		User user = new User();
		user.setId(olduser.getId());
		System.out.println(olduser.getId());

		Map<String, Object> map = new HashMap<>();
		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload sfu = new ServletFileUpload(factory);

		try {
			List<FileItem> items = sfu.parseRequest(request);
			for (FileItem item : items) {
				if (item.isFormField()) {
					String fileName = item.getFieldName();
					String fileValue = item.getString("UTF-8");
					map.put(fileName, fileValue);
				} else {
					String address = olduser.getPicPath();
					String name = address.substring(address.lastIndexOf("/") + 1);

					String photoFolder = request.getServletContext().getRealPath("admin\\images\\touxiang");

					InputStream inputStream = item.getInputStream();
					OutputStream outputStream = new FileOutputStream(photoFolder + "/" + name);
					IOUtils.copy(inputStream, outputStream);

					inputStream.close();
					outputStream.close();
					item.delete();

					map.put("picPath", address);
				}
			}
		} catch (FileUploadException e) {
			e.printStackTrace();
		}

		try {
			BeanUtils.populate(user, map);
		} catch (Exception e) {
			e.printStackTrace();
		}
		userService.updateUser(user);
		// 清除旧的session
		request.getSession().invalidate();

		request.getSession().setAttribute("user", user);
		request.getRequestDispatcher(request.getContextPath() + "/UserServlet?method=changeSelf").forward(request, response);
	}

	protected void modifyPassword(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.getRequestDispatcher("/WEB-INF/admin/pass.jsp").forward(request, response);
	}

	protected void xiuGaiPassword(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");

		int id = Integer.parseInt(request.getParameter("id"));
		System.out.println(id);

		String psw = request.getParameter("newpass");

		userService.xiuGaiPsw(id,psw);

	}

}
